 <template>
  <div class="login-container">
    <!-- 头部导航栏 -->
    <van-nav-bar title="登录">
      <template #left>
        <img src="@/assets/image/logo.png" class="logo"/>
      </template>
    </van-nav-bar>
    <!-- 表单组件 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        label="手机号"
        placeholder="手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号', trigger: 'onChange' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入合法的手机号', trigger: 'onChange' }
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="验证码"
        required
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码', trigger: 'onChange' },
          { pattern: /^\d{6}$/, message: '请输入合法的验证码', trigger: 'onChange' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="loading"
          round
          block
          type="info"
          native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { Toast } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      loading: false, // 按钮的加载状态，true表示加载中，false不加载
      formLogin: { // 登录表单数据
        mobile: '13522513531', // 手机号
        code: '246810' // 验证码
      }
    }
  },
  methods: {
    ...mapActions('user', ['asyncLoginAction']),
    async onSubmit () {
      try {
        // 提交之前把按钮设置为加载中的状态
        this.loading = true
        await this.asyncLoginAction({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        Toast.success('登录成功！')
        this.$router.replace('/layout/home')
      } catch (e) {
        Toast.fail('登录错误！')
      } finally {
        // 无论登录成功还是失败，把按钮设置为加载完毕的状态
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
